<template>
  <div class="wrap">
    <pro-table
      ref="proTableInst"
      tableTitle="字典列表"
      :columns="columns"
      :request="fetchDictPage"
      auto-height
    >
      <template #operation>
        <n-space>
          <n-button
            v-hasPermi="`dictionaryType:add`"
            type="primary"
            @click="handleAddDict"
          >
            新增
          </n-button>
        </n-space>
      </template>
    </pro-table>

    <n-drawer
      v-model:show="drawerShow"
      :width="500"
      resizable
      :maskClosable="false"
      @after-leave="resetDictForm"
    >
      <n-drawer-content closable :title="handleTag">
        <pro-form
          ref="dictFormInst"
          v-model:form="dictForm"
          :options="dictFormOptions"
          :formProps="{
            labelPlacement: 'left'
          }"
        ></pro-form>

        <template #footer>
          <n-space>
            <n-button @click="drawerShow = false">取消</n-button>
            <n-button type="primary" @click="dictConfirm">确认</n-button>
          </n-space>
        </template>
      </n-drawer-content>
    </n-drawer>
  </div>
</template>

<script lang="ts" setup name="DictList">
  import { ProTableInst } from '@/components/pro-table/type'
  import { ProFormInst } from '@/components/pro-form/type'
  import { useDictApi, useDictProForm, useDictProTable } from './hooks'
  import { DictModel } from '@/api/model/dictModel'

  console.log('DictModelDictModelDictModel')

  const proTableInst = ref<ProTableInst | null>(null)
  const dictFormInst = ref<ProFormInst | null>(null)

  const drawerShow = ref(false)
  const handleType = ref<'add' | 'edit' | ''>('')
  const handleTag = computed(() =>
    handleType.value === 'add' ? '新增字典' : '修改字典'
  )
  const { dictForm, resetDictForm, dictFormOptions } = useDictProForm()

  const handleAddDict = () => {
    handleType.value = 'add'
    drawerShow.value = true
  }

  const handleEditDict = (row: DictModel) => {
    dictForm.value = row
    handleType.value = 'edit'
    drawerShow.value = true
  }

  const dictConfirm = async () => {
    if (await dictFormInst.value?.handleSubmit()) {
      fetchAddOrEditDict()
    }
  }

  const { fetchDictPage, fetchAddOrEditDict, fetchDelDict } = useDictApi({
    handleType,
    handleTag,
    drawerShow,
    dictForm,
    proTableInst
  })
  const { columns } = useDictProTable({ handleEditDict, fetchDelDict })
</script>

<style lang="less" scoped></style>
